
import {computed, ref, type Ref} from 'vue'
import  {FlowNodeType} from '../types'
import BaseFlowNode from '../class/BaseFlowNode'
import RouteNode from '../class/flow-nodes/RouteNode'
import ExclusiveNode from '../class/flow-nodes/ExclusiveNode'
import ParallelNode from '../class/flow-nodes/ParallelNode'



let _CurSelectedNode:Ref<BaseFlowNode|null> = ref(null)
export default function useFlowNode(NodeData:Ref<Array<BaseFlowNode>>) {



  //递归找出当前节点所在分支列表
  function  findNodeByNodelist(nodeList:Array<BaseFlowNode>,nodeId:String,callback:(nodeList:Array<BaseFlowNode>,RouteNode?:RouteNode<BaseFlowNode>)=>void,RouteNode?:RouteNode<BaseFlowNode>){
    nodeList.forEach((item) => {
      if(item.getNodeId() === nodeId){
        callback(nodeList,RouteNode)
      }else{
        if(item.getNodeType() === FlowNodeType.ROUTE){
          (item as RouteNode<BaseFlowNode>).getBranchs().forEach((branch) => {
            findNodeByNodelist( branch,nodeId,callback,item as RouteNode<BaseFlowNode>)
          })
        }
      } 
    })
  }
    //根据节点Id删除节点
   function removeNode(node:BaseFlowNode){
      
      findNodeByNodelist(NodeData.value,node.getNodeId(),(nodeList,RouteNode) => {
        if(node.getNodeType() === FlowNodeType.PARALLEL||node.getNodeType() === FlowNodeType.EXCLUSIVE){
          if(RouteNode!.getBranchs().length == 2){
            removeNode(RouteNode as BaseFlowNode)
            return;
          }else{
            RouteNode!.getBranchs().splice(RouteNode!.getBranchs().findIndex((item) => item.find((item) => item.getNodeId() === node.getNodeId())),1)
            return;
          }
        }
        nodeList.splice(nodeList.findIndex((item) => item.getNodeId() === node.getNodeId()),1) 
      })
 
    }




  return {
    //当前选中节点
    CurSelectedNode:computed(()=>_CurSelectedNode.value),

    //设置选中节点
    setCurSelectedNode(node:BaseFlowNode){
      _CurSelectedNode.value = node
    },
    cancelCurSelectedNode(){
      _CurSelectedNode.value = null
    },

    //根据上一个节点Id添加新节点
    addNode(beforeNode:BaseFlowNode,node:BaseFlowNode){

      findNodeByNodelist(NodeData.value,beforeNode.getNodeId(),(nodeList) => {
          nodeList.splice(nodeList.findIndex((item) => item.getNodeId() === beforeNode.getNodeId()) + 1,0,node)
      })
    },
    removeNode,

    //给对应的路由网关节点添加分支节点
    addRouteNodeBranch(RouteNode:RouteNode<BaseFlowNode>,node:BaseFlowNode){
      findNodeByNodelist(NodeData.value,RouteNode.getNodeId(),(nodeList) => {
        RouteNode.getBranchs().push([node])
      }) 
    }

  }

}

